﻿using Newtonsoft.Json;
using QLBH.Models;
using QLBH.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace QLBH.Modules
{
    public partial class frmAdd_Edit_Orders : Form
    {
        int id;
        String ten;
        float thanhtien;
        float giasp = 0.0f;
        float tonggia = 0.0f;
        int soluong;
        float thue = 0.0f;
        float giamgia = 0.0f;
        String Trangthai = "Chua_nhap";
        private eType type = eType.ADD;
        private OrdersModel objmodel;
        public OrdersModel objModel
        {
            get { return objmodel; }
            set { objmodel = value; }
        }
        public frmAdd_Edit_Orders(eType type)
        {
            objmodel = new OrdersModel();
            InitializeComponent();
            this.type = type;
        }
        private void frmAdd_Edit_Orders_Load(object sender, EventArgs e)
        {
            CutString();
            this.dgvListOrders.AutoGenerateColumns = false;
            lbNgaytao.Text = DateTime.Now.ToShortDateString();

            listwarehouse();
            if (type == eType.EDIT)
            {
                //  txbComment.Text = objModel.Comments;
                // txbSldat.Text = objModel.Order_number.ToString();
                //txbGiamgia.Text = objModel.Discount.ToString();
                // txbThue.Text = objModel.Tax.ToString();
                //  lbTongtien.Text = objModel.Total_money.ToString();
                //txbGia.Text = objModel.Import_price.ToString();
                //   dgvHanghoa.DataSource = objModel;
                //  lbNgaysua.Text = objModel.Updated_at.ToShortDateString();
                //   lbNgaytao.Text = objModel.Created_at.ToShortDateString();
                //   cbbKhohang.SelectedValue = objModel.Warehouse_id;
                if (objModel.Status == "Da_nhap")
                {
                    rbtDanhap.Checked = true;
                }

            }

        }
        private void listwarehouse()
        {
            try
            {
                List<WarehouseModel> data = WSAccess.GetData<List<WarehouseModel>>(MainForm.Instance.Shop_id.ToString() + "/warehouse");
                cbbKhohang.DataSource = data;
                cbbKhohang.ValueMember = "id";
                cbbKhohang.DisplayMember = "name";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Tinhtoan()
        {
            try
            {
                if (txbSldat.Text != "")
                {
                    soluong = int.Parse(txbSldat.Text.ToString());
                }
                if (txbThue.Text != "")
                {
                    thue = float.Parse(txbThue.Text.ToString());
                }
                if (txbGiamgia.Text != "" && float.Parse(txbGiamgia.Text) < giasp)
                {
                    giamgia = float.Parse(txbGiamgia.Text.ToString());
                }
                if (soluong > 0 && giasp > 0)
                {
                    if (giamgia > 0 && thue > 0)
                    {
                        thanhtien = (soluong * giasp) - (soluong * giamgia);
                        thanhtien += thanhtien * thue / 100;

                    }
                    if (giamgia <= 0 && thue <= 0)
                    {
                        thanhtien = soluong * giasp;
                        lbTongtien.Text = thanhtien.ToString();
                    } if (giamgia > 0 && thue <= 0)
                    {
                        thanhtien = (soluong * giasp) - (soluong * giamgia);

                    }
                    if (thue > 0 && giamgia <= 0)
                    {
                        thanhtien = (soluong * giasp);
                        thanhtien += thanhtien * thue / 100;

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //private void Tinhtoan_Giamgiaphantram()
        //{
        //    try
        //    {
        //        if (txbSldat.Text != "")
        //        {
        //            soluong = int.Parse(txbSldat.Text.ToString());
        //        }
        //        if (txbThue.Text != "")
        //        {
        //            thue = float.Parse(txbThue.Text.ToString());
        //        }
        //        if (txbGiamgia.Text != "")
        //        {
        //            giamgia = float.Parse(txbGiamgia.Text.ToString());
        //        }
        //        if (soluong > 0 && giasp > 0)
        //        {
        //            if (giamgia > 0 && thue > 0)
        //            {
        //                thanhtien = ((soluong * giasp) * (100 - giamgia) / 100);
        //                thanhtien += thanhtien * thue / 100;

        //            }
        //            if (giamgia <= 0 && thue <= 0)
        //            {
        //                thanhtien = soluong * giasp;
        //                lbTongtien.Text = thanhtien.ToString();
        //            } if (giamgia > 0 && thue <= 0)
        //            {
        //                thanhtien = ((soluong * giasp) * (100 - giamgia) / 100);

        //            }
        //            if (thue > 0 && giamgia <= 0)
        //            {
        //                thanhtien = (soluong * giasp);
        //                thanhtien += thanhtien * thue / 100;

        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //}
        private void txbSeachname_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txbSeachname.Text != "")
                {
                    lvHanghoa.Visible = true;
                    List<GoodModel> data = WSAccess.GetData<List<GoodModel>>(txbSeachname.Text + "/good_name/goods");
                    lvHanghoa.Clear();
                    lvHanghoa.Columns.Add("Tên", 120, HorizontalAlignment.Center);
                    lvHanghoa.Columns.Add("Mã", 0, HorizontalAlignment.Center);
                    lvHanghoa.Columns.Add("Giá", 83, HorizontalAlignment.Center);
                    lvHanghoa.View = View.Details;
                    foreach (var item in data)
                    {
                        ListViewItem lvi = new ListViewItem();
                        lvi.SubItems.Add(Convert.ToString(item.Id));
                        lvi.Text = item.Name;
                        lvi.SubItems.Add(Convert.ToString(item.Import_price));
                        lvHanghoa.Items.Add(lvi);
                    }
                }
                else
                {
                    lvHanghoa.Visible = false;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnThem_Click(object sender, EventArgs e)
        {
            try
            {

                if (CheckValidate())
                    {
                       
                        int sl = Convert.ToInt32(txbSldat.Text);
                        String ghichu = txbComment.Text;
                        Tinhtoan();
                        this.dgvListOrders.Rows.Add(id, ten, giasp, soluong, thue, giamgia, ghichu, thanhtien);
                        tonggia += thanhtien;
                        lbTongtien.Text = tonggia.ToString();
                        txbComment.Text = txbGiamgia.Text = txbSldat.Text = txbSeachname.Text = ""; txbThue.Text =Convert.ToString(10);
                        txbSeachname.Focus();
                        ten = null;
                        soluong = 0;
                        giasp = 0.0f;
                        thue = 0.0f;
                        giamgia = 0.0f;
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public bool CheckValidate()
        {
            try
            {
                if (txbGiamgia.Text != "" && float.Parse(txbGiamgia.Text) > giasp)
                {
                    MessageBox.Show("Số tiền giảm giá không được lớn hơn giá sản phẩm", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txbGiamgia.Focus();
                    txbGiamgia.Focus();
                    return false;
                }else
                if (ten == null )
                {
                    MessageBox.Show("Chưa có sản phẩm nào được chọn", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txbSeachname.Focus();
                    txbSeachname.Focus();
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Lỗi",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            try
            {
                DataInputHelper.CheckIntValue(txbSldat.Text, "Số lượng đặt hàng");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Quản lý chi nhánh", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txbSldat.SelectAll();
                txbSldat.Focus();
                return false;
            }

            try
            {
                DataInputHelper.CheckTextDataLength(txbComment.Text,"Ghi chú",150);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Quản lý chi nhánh", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txbComment.SelectAll();
                txbComment.Focus();
                return false;
            }
            for (int i = 0; i < dgvListOrders.RowCount; i++)
            {
                int good_id = int.Parse(dgvListOrders.Rows[i].Cells[0].Value.ToString());
                if (id == good_id)
                {
                    MessageBox.Show("Sản phẩm đã tồn tại trong danh sách đặt hàng", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txbSeachname.Focus();
                    txbSeachname.SelectAll();
                    return false;
                }
            }

           
            return true;
        }
        private void lvHanghoa_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem lvi in lvHanghoa.SelectedItems)
            {
               
                id = Convert.ToInt32(lvi.SubItems[1].Text);
                giasp = float.Parse(lvi.SubItems[2].Text);
                ten =  lvi.SubItems[0].Text;
                txbSeachname.Text = lvi.SubItems[0].Text;
                lvHanghoa.Visible = false;

            }
           
        }
        private void CutString()
        {
            string a = "";
            string b = "";
            String Date = DateTime.Now.ToString();
            string[] word = Date.Split(' ');
            string[] date = word[0].Split('/');
            string[] h = word[1].Split(':');
            for (int i = 0; i < date.Length; i++)
            {
                a += date[i];
                b += h[i];
            }
            lbSophieu.Text = a.ToString() + b.ToString();
        }
        private void btnThemKho_Click(object sender, EventArgs e)
        {
            frmAdd_Edit_Warehouse frmWarehouse = new frmAdd_Edit_Warehouse(eType.ADD);
            frmWarehouse.ShowDialog();
        }
        private void btnHuy_Click(object sender, EventArgs e)
        {
            if (dgvListOrders.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow row in dgvListOrders.SelectedRows)
                {
                    if (!row.IsNewRow)
                        dgvListOrders.Rows.Remove(row);
                }
            }
        }
        private void btnLuuVaThoat_Click(object sender, EventArgs e)
        {
            if (rbtDanhap.Checked == true)
            {
                Trangthai = "Da_nhap";
            }
            int user_id = 1;
            int shop_id = int.Parse(MainForm.Instance.Shop_id.ToString());
            objModel.Order_number = lbSophieu.Text;
            objModel.Warehouse_id = int.Parse(cbbKhohang.SelectedValue.ToString());
            objModel.Total_money = float.Parse(lbTongtien.Text);
            objModel.User_id = user_id;
            objModel.Status = Trangthai;
            List<OrdersDetailModel> objdetail = new List<OrdersDetailModel>();
            for (int i = 0; i < dgvListOrders.RowCount; i++)
            {
                int good_id = int.Parse(dgvListOrders.Rows[i].Cells[0].Value.ToString());
                int number = int.Parse(dgvListOrders.SelectedRows[i].Cells[3].Value.ToString());
                float import_price = float.Parse(dgvListOrders.SelectedRows[i].Cells[2].Value.ToString());
                float tax = float.Parse(dgvListOrders.SelectedRows[i].Cells[4].Value.ToString());
                float discount = float.Parse(dgvListOrders.SelectedRows[i].Cells[5].Value.ToString());
                string comments = dgvListOrders.SelectedRows[i].Cells[6].Value.ToString();
                objdetail.Add(new OrdersDetailModel() { Good_id = good_id, Number = number, Import_price = import_price, Tax = tax, Discount = discount, Comments = comments });
            }

            try
            {
                if (type == eType.ADD)
                {
                    InsertResponse response = WSAccess.Insert<OrdersModel, InsertResponse>(objModel, "orders/insert/" + shop_id);
                    if (response.Status != null)
                    {
                        MessageBox.Show("Thêm mới thành công");
                    }
                }
                else
                {

                    WSAccess.Update<OrdersModel>(objModel, objModel.Id + "/branch/edit");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
    public class ResponseOrders : ResponseBase
    {
        private int order_id;
        public int Order_id
        {
            get { return order_id; }
            set { order_id = value; }
        }
    }
}
